package com.qm.console.component.aop;

import com.google.gson.Gson;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author wanghui
 *
 * 统一打印请求参数
 */
@Component
@Aspect
public class WebLogAspect {

    private final Logger LOG = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.qm.console.controller.rest.*.*(..))")
    public void webLog() {}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 打印请求相关参数
        LOG.info("========================================== Start ==========================================");
        // 打印请求 url
        LOG.info("URL            : {}", request.getRequestURL().toString());
        // 打印 Http method
        LOG.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        LOG.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        // 打印请求的 IP
        LOG.info("IP             : {}", request.getRemoteAddr());
        // 打印请求入参
        LOG.info("Request Args   : {}", request.getQueryString());
        // 打印用户信息
        if (request.getUserPrincipal() != null){
            LOG.info("Request UserInfo   : {}", request.getUserPrincipal().getName());
        }else {
            LOG.info("Request UserInfo   : {}", "not user");
        }
        LOG.info(new Gson().toJson(request.getParameterMap()));
    }
}
